package cn.com.lms.business.learning.web;

import cn.com.lms.app.api.exam.PaperApi;
import cn.com.lms.app.api.exam.vo.UserPaperDetailVO;
import cn.com.lms.business.core.constant.BNZConstants;
import cn.com.lms.business.core.util.ExportUtils;
import cn.com.lms.business.core.util.ServletUtils;
import cn.com.lms.business.core.util.SystemUserUtil;
import cn.com.lms.business.course.service.FbCourseInfoService;
import cn.com.lms.business.learning.persistence.entity.FbLearningPlan;
import cn.com.lms.business.learning.persistence.entity.FbLearningStage;
import cn.com.lms.business.learning.persistence.entity.vo.*;
import cn.com.lms.business.learning.service.LearningPlanService;
import com.bnzj.core.exception.BusinessException;
import com.bnzj.core.persistence.query.QueryHelpBean;
import com.bnzj.core.rest.ResponseResult;
import com.bnzj.core.rest.ResultCode;
import com.bnzj.core.util.DateUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

/*
 * @author liuwei
 * @date 2020/3/18 17:05
 * @desc 学习计划API
 */
@Tag(name = "学习计划功能模块", description = "学习计划功能模块")
@RestController
@RequestMapping("/learning/plan")
public class LearningPlanController {

    private final static Logger logger = LoggerFactory.getLogger(LearningPlanController.class);

    @Autowired
    private LearningPlanService learningPlanService;

    @Autowired
    private FbCourseInfoService courseInfoService;

    @Autowired
    private PaperApi paperApi;

    @GetMapping("/getLearningList")
    @Operation(summary = "查询学习计划列表", parameters = {@Parameter(name = "planName", description = "计划名称"), @Parameter(name = "stateCode", description = "状态")
            , @Parameter(name = "limit", description = "分页大小", allowReserved = true, schema = @Schema(type = "int", description = "分页大小"))
            , @Parameter(name = "offset", description = "页码", allowReserved = true, schema = @Schema(type = "int", description = "页码"))})
    public ResponseResult<Page<FbLearningPlan>> getLearningPlanList(HttpServletRequest request) {
        return ResponseResult.success(learningPlanService.queryLearningList(request));
    }

    @PostMapping("/saveLearning")
    @Operation(summary = "新增学习计划", parameters = {@Parameter(name = "learningSaveVo", required = true, description = "学习计划对象")})
    public ResponseResult saveLearning(@RequestBody LearningSaveVo learningSaveVo) {
        String date = DateUtils.formatDate(new Date(), "yyyy-MM-dd");
        Date date1 = DateUtils.parseDate(date);
        if (learningSaveVo.getFinishTime().getTime() < date1.getTime()) {
            return ResponseResult.bizException(new BusinessException("完成时间不能小于当前时间", ResultCode.FAILURE));
        }
        String finishDate = DateUtils.formatDate(learningSaveVo.getFinishTime(), "yyyy-MM-dd 23:59:59");
        learningSaveVo.setFinishTime(DateUtils.parseDate(finishDate));
        try {
            return learningPlanService.saveLearning(learningSaveVo);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        return ResponseResult.bizException(new BusinessException("操作失败", ResultCode.FAILURE));
    }


    @GetMapping("/viewLearning/{learningId}")
    @Operation(summary = "查看学习计划详情", parameters = {@Parameter(name = "learningId", required = true, description = "学习计划ID")})
    public ResponseResult viewLearning(@PathVariable Long learningId) {
        return learningPlanService.getLearningView(learningId);
    }


    @GetMapping("/delLearning/{id}/{type}")
    @Operation(summary = "删除学习计划相关信息")
    public ResponseResult delLearning(@Parameter(name = "id", required = true, description = "主键id") @PathVariable(value = "id", name = "id") Long id,
                                      @Parameter(name = "type", required = true, description = "删除类型:0 学习计划 1 阶段 2阶段详情") @PathVariable(value = "type", name = "type") Integer type) {
        return learningPlanService.delLearning(id, type);
    }

    @GetMapping("/updateLearningState")
    @Operation(summary = "撤回/发布学习计划")
    public ResponseResult updateLearningState(@Parameter(name = "learningId", required = true, description = "学习计划id") @RequestParam(value = "learningId", name = "learningId") Long learningId
            , @Parameter(name = "code", required = true, description = "操作类型") @RequestParam(value = "code", name = "code") Integer code) {
        return learningPlanService.updateLearningState(learningId, code);
    }


    @Operation(summary = "学习计划跟踪详情", parameters = {
            @Parameter(name = "learningId", required = true, description = "学习计划Id", schema = @Schema(type = "Long"))})
    @GetMapping("/getLearningView/{learningId}")
    public ResponseResult<LearningViewVo> getLearningView(HttpServletRequest request, @PathVariable(value = "learningId", name = "learningId") Long learningId) {
        return learningPlanService.getTrackLearningView(learningId, request);
    }

    @Operation(summary = "课程学习明细", parameters = {
            @Parameter(name = "id", required = true, description = "计划课程id", schema = @Schema(type = "Long"))
            , @Parameter(name = "limit", description = "分页大小", allowReserved = true, schema = @Schema(type = "int", description = "分页大小"))
            , @Parameter(name = "offset", description = "页码", allowReserved = true, schema = @Schema(type = "int", description = "页码"))
            , @Parameter(name = "finishState", required = true, description = "完成状态", schema = @Schema(type = "int"))})
    @GetMapping("/getCourseLearningView/{id}")
    public ResponseResult<LearningStageViewStuVo> getCourseLearningView(HttpServletRequest request, @PathVariable(value = "id", name = "id") Long id) {
        return learningPlanService.getCourseLearningView(id, request);
    }


    @Operation(summary = "按学员查看列表", parameters = {
            @Parameter(name = "limit", description = "分页大小", allowReserved = true, schema = @Schema(type = "int", description = "分页大小"))
            , @Parameter(name = "offset", description = "页码", allowReserved = true, schema = @Schema(type = "int", description = "页码"))
            , @Parameter(name = "learningId", required = true, description = "学习计划Id", schema = @Schema(type = "Long"))
            , @Parameter(name = "finishState", required = true, description = "完成状态0未完成 1已完成", schema = @Schema(type = "int"))
            , @Parameter(name = "templateName", required = true, description = "模板名称", schema = @Schema(type = "String"))
            , @Parameter(name = "isRecord", required = true, description = "是否备案（全部不需要传,其他传是或者否）", schema = @Schema(type = "String"))
    })
    @GetMapping("/getLearningByStudent/{learningId}")
    public ResponseResult<Page<LearningByStudentVo>> getLearningByStudent(HttpServletRequest request, @PathVariable(value = "learningId", name = "learningId") Long learningId) {
        return ResponseResult.success(learningPlanService.getLearningByStudent(learningId, request));
    }


    @Operation(summary = "按员工查看列表详情", parameters = {
            @Parameter(name = "planId", required = true, description = "计划id", schema = @Schema(type = "Long"))
            , @Parameter(name = "userId", required = true, description = "用户id", schema = @Schema(type = "Long"))})
    @GetMapping("/getCourseLearningByStuView")
    public ResponseResult<List<FbLearningStage>> getCourseLearningByStuView(HttpServletRequest request) {
        return learningPlanService.getCourseLearningByStuView(request);
    }

    @Operation(summary = "获取计划状态")
    @GetMapping("/getDictionaryList")
    public ResponseResult<List<Map<String, Object>>> getDictionaryList() {
        return ResponseResult.success(courseInfoService.getCourseTypeDictionary(BNZConstants.LEARNING_STATE_CODE));
    }


    @Operation(summary = "学习计划统计列表", parameters = {
            @Parameter(name = "planName", required = true, description = "计划名称", schema = @Schema(type = "String"))
            , @Parameter(name = "startDate", required = true, description = "开始时间", schema = @Schema(type = "Date"))
            , @Parameter(name = "endDate", required = true, description = "结束时间", schema = @Schema(type = "Date"))})
    @GetMapping("/getPlanStatisticsList")
    public ResponseResult<Page> getPlanStatisticsList(HttpServletRequest request) {
        return ResponseResult.success(learningPlanService.getPlanStatisticsList(request));
    }

    @Operation(summary = "学习计划统计列表详情导出", parameters = {
            @Parameter(name = "templateName", required = true, description = "名称,部门搜索", schema = @Schema(type = "String"))
            , @Parameter(name = "finishState", required = true, description = "完成状态 0未完成 1已完成 2延期完成 ", schema = @Schema(type = "String"))
            , @Parameter(name = "isRecord", required = true, description = "是否备案 true 是 false 否", schema = @Schema(type = "boolean"))
            , @Parameter(name = "isReadOnly", required = true, description = "是否导出只读 true 是 false 否", schema = @Schema(type = "boolean"))})
    @PostMapping("/exportStatistics/{learningId}")
    public void exportStatistics(@PathVariable(value = "learningId", name = "learningId") Long learningId, @RequestBody ExportStatisticsVo statisticsVo, HttpServletResponse response) throws IOException {
        OutputStream output = null;
        try {
            output = response.getOutputStream();
            String finishState = statisticsVo.getFinishState();
            String templateName = statisticsVo.getTemplateName();
            String isRecord = statisticsVo.getIsRecord();
            Boolean isReadOnly = statisticsVo.getIsReadOnly();
            QueryHelpBean bean = learningPlanService.getQueryStudentHelpBean(learningId, finishState, templateName, isRecord);
            bean.setPageable(ServletUtils.initPage());
            List<?> list = learningPlanService.exportAll(bean);
            String title = "学员计划完成详情";
            Workbook wb = new XSSFWorkbook();//创建HSSFWorkbook对象
            String password = "";
            if (isReadOnly) {
                //如果是导出只读的，需从数据库读取配置好的密码
                password = courseInfoService.getSysSettingValue(BNZConstants.EXCEL_PASSWORD);
            }
            if (null != SystemUserUtil.getCurrentUser() && "admin".equals(SystemUserUtil.getCurrentUser().getAccount())) {
                ExportUtils.exportExcel(wb, title, list, LearningPlanService.getColumnList(), password);
            } else {
                ExportUtils.exportExcel(wb, title, list, LearningPlanService.getAppointColumnList(), password);
            }
            //输出Excel文件

            String codedFileName = java.net.URLEncoder.encode("学习计划统计列表详情", "UTF-8");
            //设置响应头，
            response.setContentType("application/octet-stream");
            //默认Excel名称
            response.setHeader("Content-Disposition", "attachment;fileName=" + codedFileName + ".xls");

            wb.write(output);
        } catch (Exception e) {
            logger.error(e.getMessage());
//            return ResponseResult.failure(0, "导出失败，数据导出异常 ");
        } finally {
            output.flush();
            output.close();
        }
    }

    /*
     * @author liuwei
     * @date 2020/4/24 9:49
     * @desc 跟踪详情页面-按阶段查看-详情-考试
     */
    @GetMapping("/queryStageUserExamList/{stageDetailId}")
    @Operation(summary = "跟踪详情页面-按阶段查看-详情-考试", parameters = {
            @Parameter(name = "limit", description = "分页大小", allowReserved = true, schema = @Schema(type = "int", description = "分页大小"))
            , @Parameter(name = "offset", description = "页码", allowReserved = true, schema = @Schema(type = "int", description = "页码"))
            , @Parameter(name = "dateSort", description = "最近交卷时间排序（descend 降序  ascend升序）", allowReserved = true, schema = @Schema(type = "String", description = "最近交卷时间排序（descend 降序  ascend升序）"))
            , @Parameter(name = "isRecord", description = "是否备注(是，否)", allowReserved = true, schema = @Schema(type = "String", description = "是否备注"))
            , @Parameter(name = "userName", description = "学员姓名", allowReserved = true, schema = @Schema(type = "String", description = "学员姓名"))
    })
    public ResponseResult<Page<StageUserExamListVo>> queryStageUserExamList(HttpServletRequest request, @PathVariable Long stageDetailId) {
        return ResponseResult.success(learningPlanService.queryStageUserExamList(request, stageDetailId));
    }


    /*
     * @author liuwei
     * @date 2020/4/24 15:11
     * @desc 跟踪详情页面-按阶段查看-详情-考试-答题详情
     */
    @GetMapping("/stageUserExamAnswerList/{stageDetailId}")
    @Operation(summary = "跟踪详情页面-按阶段查看-详情-考试-答题详情", parameters = {
            @Parameter(name = "userId", description = "用户ID", allowReserved = true, schema = @Schema(type = "Long", description = "用户ID"))
    })
    public ResponseResult<UserPaperDetailVO> stageUserExamAnswerList(HttpServletRequest request, @PathVariable Long stageDetailId) {
        return paperApi.getUserTestDetailById(request, stageDetailId);
    }


    /*
     * @author liuwei
     * @date 2020/4/26 15:36
     * @desc 跟踪详情页面-按阶段查看-详情-问卷列表
     */
    @GetMapping("/queryStageUserQuestion/{stageDetailId}")
    @Operation(summary = "跟踪详情页面-按阶段查看-详情-问卷", parameters = {
            @Parameter(name = "limit", description = "分页大小", allowReserved = true, schema = @Schema(type = "int", description = "分页大小"))
            , @Parameter(name = "offset", description = "页码", allowReserved = true, schema = @Schema(type = "int", description = "页码"))
            , @Parameter(name = "dateSort", description = "提交时间排序（descend 降序  ascend升序）", allowReserved = true, schema = @Schema(type = "String", description = "最近交卷时间排序（descend 降序  ascend升序）"))
            , @Parameter(name = "userName", description = "学员姓名", allowReserved = true, schema = @Schema(type = "String", description = "学员姓名"))
            , @Parameter(name = "state", description = "筛选状态（不传查全部 1：已参加，0：未参加）", allowReserved = true, schema = @Schema(type = "Integer", description = "筛选状态"))
    })
    public ResponseResult<Page<StageUserExamListVo>> queryStageUserQuestion(HttpServletRequest request, @PathVariable Long stageDetailId) {
        return ResponseResult.success(learningPlanService.queryStageUserQuestion(request, stageDetailId));
    }

    /*
     * @author liuwei
     * @date 2020/4/27 9:36
     * @desc 跟踪详情页面-按阶段查看-详情-问卷列表-详情
     */
    @GetMapping("/getStageUserQuestion/{stageDetailId}")
    @Operation(summary = "跟踪详情页面-按阶段查看-详情-问卷列表-详情", parameters = {
            @Parameter(name = "userId", description = "学员Id", allowReserved = true, schema = @Schema(type = "Long", description = "学员Id"))
            , @Parameter(name = "questionnaireId", description = "问卷ID", allowReserved = true, schema = @Schema(type = "Long", description = "问卷ID"))
    })
    public ResponseResult<Set<StageUserQuestion>> getStageUserQuestion(HttpServletRequest request, @PathVariable Long stageDetailId) {
        return ResponseResult.success(learningPlanService.getStageUserQuestion(request, stageDetailId));
    }

    @GetMapping("/changeLearningIsOver/{id}")
    @Operation(summary = "完成计划改IsOver值为 1 ")
    public ResponseResult overLearning(@Parameter(name = "id", required = true, description = "主键id") @PathVariable(value = "id", name = "id") Long id) {
        return learningPlanService.overlearning(id);
    }

    @Operation(summary = "如果计划下视频看完则改变计划的isOver直")
    @GetMapping("/judgePlanIsOver/{learningId}")
    public ResponseResult judgePlanIsOver(@Parameter(name = "id", required = true, description = "主键id") @PathVariable(value = "learningId", name = "learningId") Long learningId) {
        return learningPlanService.judgeLearningOver(learningId);
    }
}
